//
//	 ______    ______    ______    
//	/\  __ \  /\  ___\  /\  ___\   
//	\ \  __<  \ \  __\_ \ \  __\_ 
//	 \ \_____\ \ \_____\ \ \_____\ 
//	  \/_____/  \/_____/  \/_____/ 
//
//	Powered by BeeFramework
//
//
//  ChatBoard.m
//  iHeima
//
//  Created by he chao on 5/29/14.
//  Copyright (c) 2014 leon. All rights reserved.
//

#import "ChatBoard.h"
#import "AppDelegate.h"
#import "ChatCell.h"
#import "ChatDB.h"
#import "MainBoard.h"
#import "MJPhoto.h"
#import "MJPhotoBrowser.h"

#pragma mark -

@interface ChatBoard()
{
	//<#@private var#>
}
@end

@implementation ChatBoard
DEF_SIGNAL(QUIT)
DEF_SIGNAL(FACE)
DEF_SIGNAL(PHOTO)
DEF_SIGNAL(SEND)
DEF_SIGNAL(CAMERA)
DEF_SIGNAL(LOCAL)
DEF_SIGNAL(PHOTO_FULL)
DEF_SIGNAL(LONGPRESS)
DEF_SIGNAL(ALERT)

- (void)load
{
    arrayMessage = [[NSMutableArray alloc] init];
    messageRequest = [[MessageRequest alloc] init];
    
}

- (void)unload
{
    [messageRequest cancelRequest];
    messageRequest = nil;
}

#pragma mark - Signal

ON_CREATE_VIEWS( signal )
{
    if (self.isMeeting) {
        self.title = @"私董会";
    }
    else {
        self.title = self.dictUser[@"username"];
    }
    self.navigationController.navigationBarHidden = NO;
    [self showBarButton:BeeUINavigationBar.LEFT image:nil];
    [self showNaviBar];
    
    [self loadContent];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillHideNotification object:nil];
    
    messageRequest.isMeeting = self.isMeeting;
    messageRequest.strRid = self.isMeeting?@"":self.dictUser[@"uid"];
    messageRequest.chatBoard = self;
    [messageRequest startRequest];
    
    [self loadCache];
}

ON_DELETE_VIEWS( signal )
{
}

ON_LAYOUT_VIEWS( signal )
{
}

ON_WILL_APPEAR( signal )
{
    if (self.isMeeting) {
        if (!btnQuit) {
            btnQuit = [BaseButton spawn];
            btnQuit.frame = CGRectMake(0, 0, 80, 44);
            [btnQuit setTitle:self.isAdmin?@"解散会议":@"退出会议" forState:UIControlStateNormal];
            [btnQuit setTitleColor:kBlueColor forState:UIControlStateNormal];
            [btnQuit addSignal:ChatBoard.ALERT forControlEvents:UIControlEventTouchUpInside];
        }
        [self.navigationController.navigationBar addSubview:btnQuit];
    }
    else {
        [self showBarButton:BeeUINavigationBar.LEFT image:IMAGESTRING(@"navi_back")];
    }
    
}

ON_DID_APPEAR( signal )
{
}

ON_WILL_DISAPPEAR( signal )
{
    [messageRequest cancelRequest];
    if (btnQuit) {
        [btnQuit removeFromSuperview];
    }
}

ON_DID_DISAPPEAR( signal )
{
}

ON_SIGNAL3( BeeUINavigationBar, LEFT_TOUCHED, signal )
{
    [self.stack popBoardAnimated:YES];
}

ON_SIGNAL3( BeeUINavigationBar, RIGHT_TOUCHED, signal )
{
}

ON_SIGNAL2(ChatBoard, signal){
    if ([signal is:ChatBoard.ALERT]) {
        if (self.isMeeting) {
            BeeUIAlertView *alertView = [BeeUIAlertView spawn];
            alertView.message = self.isAdmin?@"您确定要解散此私董会？":@"您确定要退出此私董会？";
            [alertView addCancelTitle:@"取消"];
            [alertView addButtonTitle:self.isAdmin?@"解散":@"退出" signal:ChatBoard.QUIT];
            [alertView showInViewController:self];
        }
        else {
            [self.stack popBoardAnimated:YES];
        }
    }
    if ([signal is:ChatBoard.QUIT]) {
        if (self.isAdmin) {
            BeeHTTPRequest *request = [self POST:[NSString stringWithFormat:@"%@/apichat/endboard",kBaseUrl]].PARAM(@"uid",kUserInfo[@"uid"]).PARAM(@"bid",self.dictMeeting[@"id"]);
            request.tag = 9531;
        }
        else {
            BeeHTTPRequest *request = [self POST:[NSString stringWithFormat:@"%@/apichat/endboard",kBaseUrl]].PARAM(@"uid",kUserInfo[@"uid"]).PARAM(@"bid",self.dictMeeting[@"id"]);
            request.tag = 9532;
        }
    }
    else if ([signal is:ChatBoard.FACE]) {
        [field resignFirstResponder];
        
        if (!facePageCtrl) {
            facePageCtrl = [[CVScrollPageViewController alloc] init];
        }
        facePageCtrl.frame = CGRectMake(0, self.viewHeight-160-64, self.viewWidth, 160);
        facePageCtrl.view.hidden = NO;
        facePageCtrl.view.backgroundColor = RGB(239, 239, 239);
        [facePageCtrl setDelegate:self];
        facePageCtrl.pageCount = 3;
        facePageCtrl.pageControlFrame = CGRectMake(0, 140, self.viewWidth, 20);
        [facePageCtrl reloadData];
        
        imgToolBar.frame = CGRectMake(0, facePageCtrl.frame.origin.y-imgToolBar.height, imgToolBar.width, imgToolBar.height);
        [self.view addSubview:facePageCtrl.view];
    }
    else if ([signal is:ChatBoard.PHOTO]){
        BeeUIActionSheet *sheet = [BeeUIActionSheet spawn];
        sheet.title = @"请选择操作";
        [sheet addButtonTitle:@"拍照" signal:ChatBoard.CAMERA];
        [sheet addButtonTitle:@"从相册选择" signal:ChatBoard.LOCAL];
        [sheet addCancelTitle:@"取消"];
        [sheet showInViewController:self];
    }
    else if ([signal is:ChatBoard.CAMERA]) {
        UIImagePickerController * c = [[UIImagePickerController alloc] init];
        c.delegate = self;
        c.sourceType = UIImagePickerControllerSourceTypeCamera;
        //c.allowsEditing = YES;
        [self presentViewController:c animated:YES completion:nil];
    }
    else if ([signal is:ChatBoard.LOCAL]) {
        UIImagePickerController * c = [[UIImagePickerController alloc] init];
        c.delegate = self;
        c.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        //c.allowsEditing = YES;
        [self presentViewController:c animated:YES completion:nil];
    }
    else if ([signal is:ChatBoard.SEND]) {
        if (facePageCtrl.view.hidden==NO) {
            facePageCtrl.view.hidden = YES;
            imgToolBar.frame = CGRectMake(0, self.viewHeight-50-(IOS7_OR_LATER?64:44), self.viewWidth, 50);
        }
        
        [field resignFirstResponder];
        [self sendMsg];
    }
    else if ([signal is:ChatBoard.LONGPRESS]){
    }
    else if ([signal is:ChatBoard.PHOTO_FULL]) {
        NSMutableArray *photos = [NSMutableArray arrayWithCapacity:1];
        
        MJPhoto *photo = [[MJPhoto alloc] init];
        photo.url = [NSURL URLWithString:[NSString stringWithFormat:@"%@/%@",kBaseUrl,signal.object]]; // 图片路径
        //photo.strDescription = arrayPhotos[i][@"description"];
        photo.srcImageView = signal.source;
        [photos addObject:photo];
        
        MJPhotoBrowser *browser = [[MJPhotoBrowser alloc] init];
        browser.currentPhotoIndex = 0; // 弹出相册时显示的第一张图片是？
        browser.photos = photos; // 设置所有的图片
        [browser show];
    }
}

ON_SIGNAL2( BeeUITextField, signal )
{
    if ([signal is:BeeUITextField.RETURN]) {
        if (field.text.length==0) {
            [[BeeUITipsCenter sharedInstance] presentMessageTips:@"请输入聊天内容"];
            return;
        }
        [field resignFirstResponder];
        [self sendMsg];
    }
    else if ([signal is:BeeUITextField.TEXT_CHANGED]) {
        if (field.text.length==0) {
            [btnSend setTitleColor:RGB(194, 194, 194) forState:UIControlStateNormal];
            btnSend.enabled = NO;
        }
        else {
            [btnSend setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            btnSend.enabled = YES;
        }
    }
}

- (void)loadCache{
    if (self.isMeeting) {
        
    }
    else {
        NSMutableArray *array = [[ChatDB sharedInstance] queryFriendMessage:self.dictUser[@"uid"]];
        
        for (int i = 0; i < array.count; i++) {
            NSMutableDictionary *dict = array[i];
            [self getshowTimeStatus:dict pre:[arrayMessage lastObject]];
            [self getCellHeight:dict];
            [arrayMessage addObject:dict];
        }
        
        [myTableView reloadData];
    }
}

- (void)sendMsg{
    BeeHTTPRequest *request = [self POST:[NSString stringWithFormat:@"%@/apichat/sendmessage",kBaseUrl]].PARAM(@"uid",kUserInfo[@"uid"]);
    if (self.isMeeting) {
        request.PARAM(@"type",@"1");
        request.PARAM(@"rid",self.dictMeeting[@"id"]);
        request.tag = 9527;
    }
    else {
        request.PARAM(@"type",@"0");
        request.PARAM(@"rid",self.dictUser[@"uid"]);
        request.tag = 9528;
    }
    request.PARAM(@"content",field.text);
    
    
}

- (void)receiveMsg:(NSMutableArray *)array{
    NSLog(@"zz");
    for (int i = 0; i < array.count; i++) {
        NSMutableDictionary *dict = array[i];
        if ([dict[@"images"] count]>0 && [dict[@"content_type"] intValue]==2) {
            [dict setObject:dict[@"images"][0][@"path"] forKey:@"content"];
        }
        [self getshowTimeStatus:dict pre:[arrayMessage lastObject]];
        [self getCellHeight:dict];
        [arrayMessage addObject:dict];
    }
    [myTableView reloadData];
    
    [self scrollTableToFoot:YES];
}

- (void)handleRequest:(BeeRequest *)request
{
    if(request.failed)
    {
        [[BeeUITipsCenter sharedInstance] dismissTips];
        NETWORK_ERROR
    }
    else if (request.succeed)
    {
        id json = [request.responseString mutableObjectFromJSONString];
        NSLog(@"%@",json);
        switch ([json[@"status"] intValue]) {
            case 1:
            {
                field.text = @"";
                switch (request.tag) {
                    case 9527:
                    {
                        NSMutableDictionary *dict = json[@"res"];
                        [self getshowTimeStatus:dict pre:[arrayMessage lastObject]];
                        [self getCellHeight:dict];
                        [arrayMessage addObject:dict];
                        
                        [[ChatDB sharedInstance] insert:dict];
                    }
                        break;
                    case 9528:
                    {
                        NSMutableDictionary *dict = json[@"res"];
                        [self getshowTimeStatus:dict pre:[arrayMessage lastObject]];
                        [self getCellHeight:dict];
                        [arrayMessage addObject:dict];
                        
                        [[ChatDB sharedInstance] insert:dict];
                        
                        
                    }
                        break;
                    case 9529:
                    {
                        NSMutableDictionary *dict = json[@"res"];
                        if ([dict[@"images"] count]>0) {
                            [dict setObject:dict[@"images"][0][@"path"] forKey:@"content"];
                        }
                        [self getshowTimeStatus:dict pre:[arrayMessage lastObject]];
                        [self getCellHeight:dict];
                        [arrayMessage addObject:dict];
                        
                        [[ChatDB sharedInstance] insert:dict];
                    }
                        break;
                    case 9530:
                    {
                        NSMutableDictionary *dict = json[@"res"];
                        if ([dict[@"images"] count]>0) {
                            [dict setObject:dict[@"images"][0][@"path"] forKey:@"content"];
                        }
                        [self getshowTimeStatus:dict pre:[arrayMessage lastObject]];
                        [self getCellHeight:dict];
                        [arrayMessage addObject:dict];
                        
                        [[ChatDB sharedInstance] insert:dict];
                    }
                        break;
                    case 9531:
                    case 9532:
                    {
                        [self.stack popToBoard:[MainBoard sharedInstance] animated:YES];
                    }
                        break;
                        
                    default:
                        break;
                }
                //                [[NSUserDefaults standardUserDefaults] setObject:json[@"res"] forKey:@"userInfo"];
                //                [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"hasLogin"];
                //                MainBoard *board = [MainBoard sharedInstance];
                //                [self.stack pushBoard:board animated:YES];
                //NSArray *array = json[@"res"];
//                [arrayUser removeAllObjects];
//                for (int i = 0; i < array.count; i++) {
//                    BOOL isFind = NO;
//                    for (int j = 0; j < arrayUser.count; j++) {
//                        if ([arrayUser[j][0][@"ind"] isEqualToString:array[i][@"ind"]]) {
//                            [arrayUser[j] addObject:array[i]];
//                            isFind = YES;
//                        }
//                    }
//                    if (!isFind) {
//                        [arrayUser addObject:[NSMutableArray arrayWithObject:array[i]]];
//                    }
//                }
                
                [myTableView reloadData];
                [self scrollTableToFoot:YES];
            }
                break;
                
            default:
                break;
        }
    }
}

- (void)sendImage:(UIImage *)image{
    BeeHTTPRequest *request = [self POST:[NSString stringWithFormat:@"%@/apichat/sendmessage",kBaseUrl]].PARAM(@"uid",kUserInfo[@"uid"]).FILE(@"img0",UIImageJPEGRepresentation(image, 0.4));
    if (self.isMeeting) {
        request.PARAM(@"type",@"1");
        request.PARAM(@"rid",self.dictMeeting[@"id"]);
        request.tag = 9529;
    }
    else {
        request.PARAM(@"type",@"0");
        request.PARAM(@"rid",self.dictUser[@"uid"]);
        request.tag = 9530;
    }
}

- (void)didScrollToPageAtIndex:(NSUInteger)index {
}

- (UIView *)scrollPageView:(id)scrollPageView viewForPageAtIndex:(NSUInteger)index {
    UIView *pageView;
    pageView = (UIView *)[scrollPageView dequeueReusablePage:index];
    if (nil == pageView) {
        pageView = [[UIView alloc] initWithFrame:facePageCtrl.view.bounds];
    }
    for (id element in pageView.subviews) {
        [element removeFromSuperview];
    }
    
    for (int i = 0; i < 7; i++) {
        for (int j = 0; j < 3; j++) {
            BeeUIButton *btnFace = [BeeUIButton spawn];
            btnFace.frame = CGRectMake(i*self.viewWidth/7.0, j*40, self.viewWidth/7.0, self.viewWidth/7.0);
            if (i==6 && j==2) {
                [btnFace setImage:IMAGESTRING(@"face_del_ico_dafeult.png") forState:UIControlStateNormal];
            }
            else {
                int source = j*7+i+index*20+1;
                btnFace.tag = source;
                NSString *strSource = [NSString stringWithFormat:@"face_%d",source];
                [btnFace setImage:IMAGESTRING(strSource) forState:UIControlStateNormal];
                [btnFace addTarget:self action:@selector(clickFace:) forControlEvents:UIControlEventTouchUpInside];
                //[btnFace addSignal:TeamChatBoard.FACE_CHAT forControlEvents:UIControlEventTouchUpInside object:strSource];
            }
            [pageView addSubview:btnFace];
        }
    }
    return pageView;
}

- (void)clickFace:(BeeUIButton *)btn{
    NSString *strSource = [NSString stringWithFormat:@"face_%d.png",btn.tag];
    AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    NSMutableDictionary *dictFace = delegate.dictFace;
    
    NSString *strKey;
    for (int j = 0; j<=[[dictFace allKeys]count]-1; j++) {
        if ([[dictFace objectForKey:[[dictFace allKeys]objectAtIndex:j]] isEqual:strSource]) {
            strKey = [[dictFace allKeys] objectAtIndex:j];
        }
    }
    
    field.text = [NSString stringWithFormat:@"%@%@",field.text,strKey];
    
    [btnSend setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    btnSend.enabled = YES;
}


- (void)loadContent{
    if (self.isMeeting) {
        BeeUIImageView *imgAvatarBg = [BeeUIImageView spawn];
        imgAvatarBg.frame = CGRectMake(0, 0, self.viewWidth, 45);
        imgAvatarBg.contentMode = UIViewContentModeScaleToFill;
        imgAvatarBg.image = IMAGESTRING(@"search_bg");
        [self.view addSubview:imgAvatarBg];
        
        for (int i = 0; i < 6; i++) {
            AvatarView *avatar = [AvatarView initFrame:CGRectMake(6+36*i, 7, 30, 30) image:nil borderColor:[UIColor clearColor]];
            //avatar.backgroundColor = [UIColor blackColor];
            [imgAvatarBg addSubview:avatar];
            if (self.arrayMeetingMember.count>i) {
                NSString *strUrl = [NSString stringWithFormat:@"%@avatar.php?uid=%@&size=middle",kPicUrl,self.arrayMeetingMember[i][@"uid"]];
                [avatar setImageWithURL:strUrl placeholderImage:IMAGESTRING(@"default_avatar")];
            }
        }
    }
    
    myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.viewWidth, self.viewHeight-50-(IOS7_OR_LATER?64:44))];
    if (self.isMeeting) {
        myTableView.frame = CGRectMake(0, 45, self.viewWidth, self.viewHeight-50-45-(IOS7_OR_LATER?64:44));
    }
    myTableView.delegate = self;
    myTableView.dataSource = self;
    myTableView.backgroundColor = [UIColor clearColor];
    myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:myTableView];
    
    imgToolBar = [BeeUIImageView spawn];
    imgToolBar.image = IMAGESTRING(@"chat_toolbar");
    imgToolBar.contentMode = UIViewContentModeScaleToFill;
    imgToolBar.frame = CGRectMake(0, self.viewHeight-50-(IOS7_OR_LATER?64:44), self.viewWidth, 50);
    imgToolBar.userInteractionEnabled = YES;
    [self.view addSubview:imgToolBar];
    
    
    BeeUIButton *btnFace = [BeeUIButton spawn];
    [btnFace setImage:IMAGESTRING(@"chat_face_btn") forState:UIControlStateNormal];
    btnFace.frame = CGRectMake(0, 0, 40, 50);
    [btnFace addSignal:ChatBoard.FACE forControlEvents:UIControlEventTouchUpInside];
    [imgToolBar addSubview:btnFace];
    
    field = [BeeUITextField spawn];
    field.frame = CGRectMake(btnFace.right, 10, 183, 30);
    field.backgroundImage = IMAGESTRING(@"chat_input");
    field.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    field.clearButtonMode = UITextFieldViewModeWhileEditing;
    field.returnKeyType = UIReturnKeySend;
    field.leftViewMode = UITextFieldViewModeAlways;
    field.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 0)];
    field.font = FONT(15);
    [imgToolBar addSubview:field];
    
    
    BeeUIButton *btnPhoto = [BeeUIButton spawn];
    [btnPhoto setImage:IMAGESTRING(@"chat_choose_img") forState:UIControlStateNormal];
    btnPhoto.frame = CGRectMake(field.right, 0, 38, 50);
    [btnPhoto addSignal:ChatBoard.PHOTO forControlEvents:UIControlEventTouchUpInside];
    [imgToolBar addSubview:btnPhoto];
    
    btnSend = [BeeUIButton spawn];
    [btnSend setTitle:@"发送" forState:UIControlStateNormal];
    btnSend.frame = CGRectMake(btnPhoto.right, 0, self.viewWidth-btnPhoto.right, 50);
    [btnSend addSignal:ChatBoard.SEND forControlEvents:UIControlEventTouchUpInside];
    [btnSend setTitleColor:RGB(194, 194, 194) forState:UIControlStateNormal];
    [btnSend setTitleFont:FONT(15)];
    btnSend.enabled = NO;
    [imgToolBar addSubview:btnSend];
}

- (void)getCellHeight:(NSMutableDictionary *)dictMessage{
    switch ([dictMessage[@"content_type"] integerValue]) {
        case 1:
        {
            MojiView *mojiView = [[MojiView alloc] init];
            [mojiView setContent:dictMessage[@"content"]];
            
            int height = 70;
            if (mojiView.height+40>70) {
                height = mojiView.height+40;
            }
            if ([dictMessage[@"showTime"] boolValue]) {
                height += 30;
            }
            [dictMessage setObject:[NSString stringWithFormat:@"%d",height] forKey:@"height"];
        }
            break;
        case 2:
        {
            int height = 115;
            if ([dictMessage[@"showTime"] boolValue]) {
                height += 30;
            }
            [dictMessage setObject:[NSString stringWithFormat:@"%d",height] forKey:@"height"];
        }
            break;
        case 3:
        {
            [dictMessage setObject:@"25" forKey:@"height"];
        }
            break;
            
        default:
            break;
    }
}

- (void)getshowTimeStatus:(NSMutableDictionary *)dict pre:(NSMutableDictionary *)dictPre{
    if (!dictPre) {
        [dict setObject:@YES forKey:@"showTime"];
    }
    else {
        NSTimeInterval t1 = [dict[@"create_at"] doubleValue];
        NSTimeInterval t2 = [dictPre[@"create_at"] doubleValue];
        NSTimeInterval leave = t1 - t2;
        if (leave>=5*60) {
            [dict setObject:@"YES" forKey:@"showTime"];
        }
        else {
            [dict setObject:@"NO" forKey:@"showTime"];
        }
    }
}

- (void)scrollTableToFoot:(BOOL)animated {
    NSInteger s = [myTableView numberOfSections];
	if (s<1) return;
	NSInteger r = [myTableView numberOfRowsInSection:s-1];
	if (r<1) return;
	
	NSIndexPath *ip = [NSIndexPath indexPathForRow:r-1 inSection:s-1];
	
	[myTableView scrollToRowAtIndexPath:ip atScrollPosition:UITableViewScrollPositionBottom animated:animated];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [arrayMessage count];
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return [arrayMessage[indexPath.row][@"height"] floatValue];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ChatCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (nil == cell) {
        cell = [[ChatCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
        cell.isFriendChat = !self.isMeeting;//self.isFriendChat;
        [cell initSelf];
    }
    cell.backgroundColor = [UIColor clearColor];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.dictMessage = arrayMessage[indexPath.row];
    [cell load];
    return cell;
}

- (void)keyboardWillChangeFrame:(NSNotification *)notification{
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_3_2
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
#endif
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_3_2
        NSValue *keyboardBoundsValue = [[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey];
#else
        NSValue *keyboardBoundsValue = [[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey];
#endif
        CGRect keyboardBounds;
        [keyboardBoundsValue getValue:&keyboardBounds];
        
        
        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDuration:0.1];
        CGRect frameView = imgToolBar.frame;
        
        CGFloat height = [[UIScreen mainScreen] bounds].size.height;
        CGFloat inputHeight = imgToolBar.height;
        CGFloat y = keyboardBounds.origin.y;
        if (y>height) {
            y = height;
        }
        //CGFloat keyHeight = keyboardBounds.size.height;
        
        frameView.origin.y = y - inputHeight-64;
        myTableView.frame = CGRectMake(0, myTableView.top, self.viewWidth, frameView.origin.y);
        
        //frameView.origin.y = y - inputHeight-20-44;
        //        if (y == height) {
        //            frameView.origin.y = y;
        //        }
        //        else {
        imgToolBar.frame = frameView;
        //        }
        
        [UIView commitAnimations];
        
        
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_3_2
    }
#endif
}

#pragma mark - QBImagePickerControllerDelegate

- (void)imagePickerController:(UIImagePickerController *)imagePickerController didFinishPickingMediaWithInfo:(id)info
{
    
    UIImage * i = [info[@"UIImagePickerControllerOriginalImage"] copy];
    if(i.size.width > 640)
    {
        i = [self scaleImage:i toScale:640/i.size.width];
    }
    
    [self dismissViewControllerAnimated:YES completion:NULL];
    [self sendImage:i];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)imagePickerController
{
    NSLog(@"Cancelled");
    
    [self dismissViewControllerAnimated:YES completion:NULL];
}

- (UIImage *)scaleImage:(UIImage *)image toScale:(float)scaleSize
{
    UIGraphicsBeginImageContext(CGSizeMake(image.size.width * scaleSize, image.size.height * scaleSize));
    [image drawInRect:CGRectMake(0, 0, image.size.width * scaleSize, image.size.height * scaleSize)];
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return scaledImage;
}

@end
